<template>
  <div class="clientDoc">
    <div class="operation">
      <el-button type="primary" icon="el-icon-plus" @click="newClient"
        >新建</el-button
      >
      <el-button icon="el-icon-takeaway-box" @click="inventory"
        >库存调转</el-button
      >
      <el-button icon="el-icon-document-add" @click="infoDoc"
        >资料建档</el-button
      >
      <el-button style="z-index: 2" icon="el-icon-edit-outline" @click="editDoc"
        >编辑</el-button
      >
      <el-button icon="el-icon-circle-check" @click="power" :disabled="Dis"
        >授权</el-button
      >
      <!-- <el-button icon="el-icon-download">导入</el-button> -->
      <!-- <div class="dr">
        <i class="el-icon-download"></i>
        导入
        <input
          ref="upload"
          accept=".xls, .xlsx"
          class="outputlist_upload"
          type="file"
        />
      </div> -->

      <el-button size="small" class="a-upload">
        <i class="el-icon-download"></i>导入
        <template>
          <input
            type="file"
            accept=".xlsx,.xls"
            @change="hanldeInsertClick"
            class="file"
          />
        </template>
      </el-button>

      <el-button @click="EXp" icon="el-icon-upload2" :disabled="jxOutCusInfo"
        >导出</el-button
      >
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
    </div>

    <el-table
      :data="clientData"
      highlight-current-row
      tooltip-effect="dark"
      id="outTable"
      height="80vh"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      @row-dblclick="dbClick"
      @row-click="rowClick"
    >
      <el-table-column prop="no" label="编号" width="60"> </el-table-column>
      <el-table-column
        prop="name"
        label="简称"
        show-overflow-tooltip
        width="120"
      >
      </el-table-column>
      <el-table-column prop="isAuthorization" label="授权" width="80">
      </el-table-column>
      <el-table-column prop="type" label="类型" width="60"> </el-table-column>
      <el-table-column prop="sellDiscount" label="销货折数" width="80">
      </el-table-column>
      <el-table-column
        prop="contact"
        label="联系人"
        width="80"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="cellphone" label="手机" width="160">
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="160"> </el-table-column>
      <el-table-column prop="fax" label="传真" width="160"> </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        width="200"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        width="200"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="business" label="业务" width="80">
      </el-table-column>
      <el-table-column prop="area" label="地区" width="110"> </el-table-column>
      <el-table-column prop="orderFormAllocateCargo" label="订配货" width="80">
      </el-table-column>
      <el-table-column prop="principal" label="负责人" width="80">
      </el-table-column>
      <el-table-column prop="postcode" label="邮编" width="100">
      </el-table-column>
      <el-table-column prop="refundRate" label="退货率" width="80">
      </el-table-column>
      <el-table-column prop="inputDiscount" label="进货折数" width="80">
      </el-table-column>
      <el-table-column prop="cashDeposit" label="保证金" width="80">
      </el-table-column>
      <el-table-column prop="nameAll" label="客户" width="80">
      </el-table-column>
      <el-table-column prop="headquartersNo" label="总店编号" width="80">
      </el-table-column>
      <el-table-column prop="stop" label="停用" width="80"> </el-table-column>
      <el-table-column prop="outMoneyFloor" label="出货金额下限" width="110">
      </el-table-column>
      <el-table-column prop="personnelCount" label="营业人员" width="110">
      </el-table-column>
      <el-table-column prop="acreage" label="面积" width="110">
      </el-table-column>
    </el-table>

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>

    <div class="mask" :style="{ display: showMask }"></div>

    <new-client
      :style="{ display: showNewClient }"
      @closeNewClient="closeNewClient"
      @postClientSuccess="postClientSuccess"
      :details="details"
      :SendData="SendData"
      :sendList="sendList"
      :showType="showType"
    >
    </new-client>

    <inventory
      :style="{ display: showInventory }"
      @closeInventory="closeInventory"
    >
    </inventory>

    <info-doc
      :customerNo="no"
      :name="name"
      :style="{ display: showInfoDoc }"
      @closeInfoDoc="closeInfoDoc"
    >
    </info-doc>
  </div>
</template>

<script>
import footView from '../../../components/FootView'
import newClient from './childComps/NewClient'
import inventory from './childComps/Inventory'
import infoDoc from './childComps/InfoDoc'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import {
  getClient,
  postClient,
  postClientList,
  deleteClient,
  postExcelClient,
  getBrand,
  getPower
} from '../../../network/client'
import outex from '../../../components/mixins/outexp'
import enterUp from '../../../components/mixins/enterUp'
import { get } from '../../../network/customerOrderTotal'
import cookieFn from '../../../components/mixins/cookieFn'

export default {
  name: 'clientDoc',
  mixins: [outex, enterUp, cookieFn],
  created() {
    this._getClient()
    // 总条数，总页码赋值
    getClient({ limit: this.limit, page: this.currentPage }).then((res) => {
      // console.log(res.data.data.length)
      this.dataLen = res.data.total
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    })
    this.inpList = this.getInput()
  },
  data() {
    return {
      Dis: true,
      dr: [],
      SendData: [],
      ListData: [],
      ListData1: [],
      customerNo: '',
      No: '',
      inpList: [],
      showType: '',
      JList: [],
      outputs: [],
      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      clientData: [],
      showMask: 'none',
      showNewClient: 'none',
      showInventory: 'none',
      showInfoDoc: 'none',
      id: '',
      no: '',
      name: '',
      details: {},
      sendList: [],

      jxQuarter: this.getCookie('jxQuarter'),
      jxOutCusInfo: this.getCookie('jxOutCusInfo') == '0'
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  },
  components: {
    footView,
    newClient,
    inventory,
    infoDoc
  },
  methods: {
    //授权
    power() {
      for (let a of [this.details]) {
        if (a.isAuthorization == '未授权') {
          a.isAuthorization = 0
        }
        if (a.isAuthorization == '已授权') {
          a.isAuthorization = 1
        }
        // console.log(this.details)
        getPower(this.details).then((res) => {
          // console.log(res.data)
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '授权成功,初始密码为:666666'
            })
          } else {
            this.$message.error({
              message: '授权失败'
            })
          }
        })
      }
    },
    EXp() {
      getClient().then((res) => {
        this.clientData = res.data.data

        this.$nextTick(() => {
          this.exp()
          this._getClient({ limit: this.limit, page: this.currentPage })
        })
      })
    },
    _getClient(params = {}) {
      getClient(params).then((res) => {
        // console.log(res.data, '_getClient')
        res.data.data.forEach((element) => {
          if (element.isAuthorization == 0) {
            element.isAuthorization = '未授权'
          }
          if (element.isAuthorization == 1) {
            element.isAuthorization = '已授权'
          }
        })
        this.clientData = res.data.data
        if (this.clientData.length == 0 && this.currentPage > 1) {
          this.currentPage--
          this._getArtNo({ limit: this.limit, page: this.currentPage })
        }
      })
    },
    //删除
    dele() {
      if (this.id == '') {
        this.$message({
          message: '请选择要删除数据',
          type: 'warning'
        })
        return
      }
      let obj = { id: this.id }
      this.$confirm('是否删除此客户编号的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteClient(obj)
          .then((res) => {
            if (res.data.code == 200) {
              this.dataLen--
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this._getClient({ limit: this.limit, page: this.currentPage })
              this.id = ''
            } else if (res.data.code == 204) {
              this.$message.error({
                message: '该数据有关联数据, 删除失败'
              })
            } else {
              this.$message.error({
                message: '删除失败'
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',

              message: '已取消删除'
            })
          })
      })
    },

    newClient() {
      this.sendList = this.clientData
      this.showMask = 'block'
      this.showNewClient = 'block'
      this.showType = '新建'
    },
    inventory() {
      this.showMask = 'block'
      this.showInventory = 'block'
    },
    infoDoc() {
      if (this.no == '') {
        this.$message({
          type: 'warning',

          message: '请选择要建档的客户!'
        })
        return
      } else {
        this.showMask = 'block'
        this.showInfoDoc = 'block'
      }
      this.showMask = 'block'
      this.showInfoDoc = 'block'
    },
    closeNewClient() {
      this.details = {}
      this.showMask = 'none'
      this.showNewClient = 'none'
      this.showType = ''
    },
    postClientSuccess() {
      this.dataLen++
      this._getClient({ limit: this.limit, page: this.currentPage })
    },
    closeInventory() {
      this.showMask = 'none'
      this.showInventory = 'none'
    },
    closeInfoDoc() {
      this.showMask = 'none'
      this.showInfoDoc = 'none'
    },

    rowClick(e) {
      this.id = e.id
      this.no = e.no
      this.name = e.name
      this.details = e
      for (let r of [this.details]) {
        // console.log(r.authorizationPhone)
        // console.log(r.isAuthorization)
        if (
          r.authorizationPhone == '' ||
          r.authorizationPhone == null ||
          r.isAuthorization == '已授权'
        ) {
          this.Dis = true
        } else {
          this.Dis = false
        }
      }
    },

    find() {
      for (let a of [this.details]) {
        this.customerNo = a.no
        // console.log(a.no)
      }
      getBrand({ customerNo: this.customerNo }).then((res) => {
        // console.log(res.data)
        this.SendData = res.data.data
        // console.log(this.SendData)
        // }
      })
    },

    dbClick(e) {
      this.sendList = []
      for (let u of this.clientData) {
        if (e.headquartersNo == u.headquartersNo) {
          this.sendList.push(u)
        }
      }
      for (let a of [this.details]) {
        // console.log(a.no)
      }
      this.find()
      this.details = e
      this.showMask = 'block'
      this.showNewClient = 'block'
      this.showType = '编辑'
    },

    editDoc() {
      if (this.details.id == '' || this.details.id == undefined) {
        this.$message({
          type: 'warning',
          message: '请选择一条数据进行编辑'
        })
        return
      }
      this.sendList = []
      for (let y of [this.details]) {
        // console.log(y)
        for (let u of this.clientData) {
          if (y.headquartersNo == u.headquartersNo) {
            this.sendList.push(u)
          }
        }
      }

      this.find()
      this.showMask = 'block'
      this.showNewClient = 'block'
      this.showType = '编辑'
    },

    readExcel(e) {
      //表格导入
      var that = this
      const files = e.target.files
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          // console.log(ws);
          var lo = JSON.parse(JSON.stringify(ws).replace(/^\[|\]$/g, ''))
          console.log(lo)
          return
          // for(var a=0;a<ws.length;a++){
          //     this.JList.push(JSON.stringify(ws[a]));
          //   }
          //   // console.log(this.JList)
          //   var kList = this.JList.replace(/^\[|\]$/g,'')
          //   console.log(kList)
          //   var lList = kList.replace(/^\"|\"$/g,'')
          //   console.log(lList)
          // // let obj = {paramsList:ac,fieldMap:{brandedCompany:"123456"}}

          // let obj = {paramsList:this.JList,fieldMap:{brandedCompany:this.brandedCompany}}
          // console.log({obj})
          for (let s of ws) {
            // console.log(s.客户编号)
            this.dr.push({
              no: s.客户编号,
              name: s.客户简称,
              type: s.类型,
              sellDiscount: s.销货折数,
              contact: s.联系人,
              cellphone: s.手机,
              phone: s.电话,
              fax: s.传真,
              address: s.地址,
              remark: s.备注,
              business: s.业务,
              area: s.地区,
              orderFormAllocateCargo: s.订配货,
              outMoneyFloor: s.出货金额下限,
              stop: s.停用,
              principal: s.负责人,
              postcode: s.邮编,
              refundRate: s.退货率,
              inputDiscount: s.进货折数,
              cashDeposit: s.保证金,
              nameAll: s.客户,
              headquartersNo: s.总店编号,
              authorizationPhone: s.授权手机号
            })
          }
          // console.log(
          //   JSON.parse(JSON.stringify(this.dr).replace(/^\[|\]$/g, ''))
          // )

          postClient(
            JSON.parse(JSON.stringify(this.dr).replace(/^\[|\]$/g, ''))
          ).then((res) => {
            // console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',

                message: '导入成功!'
              })
              this._getClient({ limit: this.limit, page: this.currentPage }) //重新请求页面数据
            } else {
              this.$message.error({
                message: '导入失败，客户编号重复!'
              })
            }
          })

          that.outputs = [] //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            }
            that.outputs.push(sheetData)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          console.log(1)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      // 总页码赋值
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      this._getClient({ limit: this.limit, page: this.currentPage })
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getClient({ limit: this.limit, page: this.currentPage })
    },

    /**
     * 新增
     */
    // 批量导入
    hanldeInsertClick(evt) {
      const { files } = evt.target
      let fileReader = new FileReader()
      fileReader.onload = async (event) => {
        try {
          const { result } = event.target
          // 以二进制流方式读取得到整份excel表格对象
          const workbook = XLSX.read(result, { type: 'binary' })
          let tableList = [] // 存储获取到的数据
          // 遍历每张工作表进行读取（这里默认只读取第一张表）
          for (const sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              // 利用 sheet_to_json 方法将 excel 转成 json 数据
              tableList = tableList.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              )
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          /**
           * 1,获取导入表格的数据
           * 2,判断 head 是否正确
           * 3，根据 head 修改对应的请求参数
           */
          if (!tableList.length) return this.$message.error('导入的数据为空')
          const tableItem = tableList[0]
          const element = Object.keys(tableItem)
          const titleStr =
            '编号,简称,授权,类型,销货折数,联系人,手机,电话,传真,地址,备注,地区,订配货,负责人,退货率,进货折数,保证金,客户,总店编号,停用,出货金额下限,营业人员,面积'
          if (element.toString() !== titleStr)
            return this.$message.error('导入的表格头部不正确,请检查后再导入')

          console.log(tableList)

          // return
          let newDataList = tableList.map((item, index) => {
            return {
              no: item['编号'],
              name: item['简称'],
              type: item['类型'],
              sellDiscount: item['销货折数'],
              contact: item['联系人'],
              cellphone: item['手机'],
              phone: item['电话'],
              fax: item['传真'],
              address: item['地址'],
              remark: item['备注'],
              business: item['业务'],
              area: item['地区'],
              orderFormAllocateCargo: item['订配货'],
              outMoneyFloor: item['出货金额下限'],
              stop: item['停用'],
              principal: item['负责人'],
              postcode: item['邮编'],
              refundRate: item['退货率'],
              inputDiscount: item['进货折数'],
              cashDeposit: item['保证金'],
              nameAll: item['客户'],
              headquartersNo: item['总店编号'],
              authorizationPhone: item['授权手机号'],
              acreage: item['面积'],
              personnelCount: item['营业人员']
            }
          })
          console.log(newDataList)
          // 发送请求
          const { data } = await postClientList(newDataList)
          if (data && data.code === 200) {
            this.$message.success(data.msg)
            this._getClient({ limit: this.limit, page: this.currentPage })
          }
        } catch (e) {
          this.$message.error(e)
        }
      }

      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files[0])
    }
  }
  // mounted() {
  //   this.$refs.upload.addEventListener('change', (e) => {
  //     //绑定监听表格导入事件
  //     this.readExcel(e)
  //   })
  // }
}
</script>

<style scoped>
.clientDoc {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}

/* 按钮 */
.operation {
  padding: 15px 0;
  border-bottom: 2px solid #f4f4f4;
  margin-bottom: 15px;
  white-space: nowrap;
  display: flex;
}

/* 尾部 */
.footView span {
  float: left;
  /* margin-right: 48px; */
  line-height: 6vh;
  font-size: 14px;
}

.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
</style>
<style>
.clientDoc .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
.clientDoc .el-button + .el-button {
  margin-left: 0;
}
</style>
